package com.hjf.booking.module.user.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.hjf.booking.constants.BaseResponse;
import com.hjf.booking.module.user.dto.WxUser;
import com.hjf.booking.module.user.mapper.MpUserMapper;
import com.hjf.booking.module.user.po.MpUser;
import com.hjf.booking.module.user.service.MpUserService;
import com.hjf.booking.module.utils.HttpClientUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author hjf
 * @since 2021-02-18
 */
@Service
public class MpUserServiceImpl implements MpUserService {


    @Value("${wx_appid}")
    public String appId;

    @Value("${wx_secret}")
    public String secret;

    @Autowired
    private MpUserMapper mpUserMapper;

    @Override
    public BaseResponse login(String openId) {
        MpUser mpUser = mpUserMapper.selectByOpenId(openId);
        if(mpUser == null){
            mpUser = new MpUser();
            mpUser.setOpenid(openId);
            mpUserMapper.insertSelective(mpUser);
        }
        return BaseResponse.ok(openId);
    }

    @Override
    public BaseResponse completeInfo(WxUser wxUser) {
        String openid = wxUser.getOpenid();
        MpUser mpUser = mpUserMapper.selectByOpenId(openid);
        if(mpUser == null){
            login(openid);
        }
        BeanUtils.copyProperties(wxUser,mpUser);
        mpUserMapper.updateByPrimaryKeySelective(mpUser);
        return BaseResponse.ok();
    }


    @Override
    public JSONObject getOpenid(String code) {
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", secret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        String result = null;
        try {
            result = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session", paramMap);
        } catch (Exception e) {
            return null;
        }
        return JSONObject.parseObject(result);
    }

}
